<script setup>
import { reactive } from 'vue'
import { ref } from 'vue'
import { nextTick } from 'vue'
import { onMounted  } from 'vue'
import axios from 'axios' 
import { ElMessage } from 'element-plus'

import * as clipboard from 'clipboard-polyfill';


// do not use same name with ref

// 当前的时间
const currentTime = ref("");
// const currentDate = dayjs().format('YYYY-MM-DD');


const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
  // 初始化显示
  updateTime(); 
  // 每秒更新一次
  setInterval(updateTime, 1000); 
});



const dataForm = reactive({
  nameData: '',
  dateData: new Date().toISOString().split('T')[0],
})

const responseDataTable = ref([])
const responseDataTableDev = ref([
  {
    "details":"10.135防撞灯振动-东菱5吨-张涵（杜海波）-<span class='highlight'>许光，于江波，杜海波（耐久3小时停半小时）</span>",
    "operators":[
      {
        "name":"name",
        "phone_number":"name",

      }
    ]
  }
])

const preserveExpanded = ref(false)

// 获取表单实例
const dataFormRef = ref();


const onCreateSubmit = () => {
  
  
  // console.log(dataForm);
  // console.log(dataForm.nameData);
  // console.log(dataForm.dateData);

  axios.post(
    '/api/implent_people/search_task', 
    dataForm,
  ).then(
    response => {
      // 请求成功，处理响应数据
      console.log(response.data);
      // responseDataTable = response.data;
      responseDataTable.value = response.data.data
      ElMessage({
        message: `解析成功,返回数据${responseDataTable.value.length}条`,
        type: "success"
      })

      // console.log(response.data);
      // console.log(responseDataTable.value.length);
      // ElMessage.success('解析成功');
    }
  ).catch(
    error => {
      // 请求失败，处理错误信息
      console.error(error);
      responseDataTable.value = []

      ElMessage.error(error.response.data["msg"]);
      console.log(error);
      console.log(error.response.data["msg"]);
    }
  );

}

const onCancelSubmit = () => {
  // 重置为默认值
  dataFormRef.value?.resetFields();
  responseDataTable.value = [];


  // dataForm.value = {
  //   nameData: '',
  //   dateData: new Date().toISOString().split('T')[0],
  // };

  // nextTick(() => {
  //   dataFormRef.value?.clearValidate();
  // });
}


const copyToClipboard = (text) => {
  try {
    clipboard.writeText(text);
    ElMessage.success(`联系方式已复制至剪贴板`);
  } catch (err) {
    ElMessage.error(
      {
        showClose: true,
        duration: 0,
        message:`请手动复制:${text}`
      }  
    );
    console.error('复制失败:', err);
  }
};




defineProps({
  msg: {
    type: String,
    required: false,
  },
})
</script>

<template>

  <el-form :model="dataForm" ref="dataFormRef" label-width="auto" style="max-width: 600px">
    <el-form-item label="当前时间">
      <p>{{ currentTime }}</p>
    </el-form-item>
    <el-form-item prop="nameData" label="查询内容">
      <el-input v-model="dataForm.nameData" type="info" placeholder="请输入试验主管/实施人员"/>
    </el-form-item>
    <el-form-item prop="dateData" label="查询日期">
      <el-date-picker
        v-model="dataForm.dateData"
        type="date"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <!-- <el-form-item class="input-textarea" prop="taskData" label="输入文本">
      <el-input v-model="dataForm.taskData" type="textarea" />
    </el-form-item> -->
    <el-form-item class="center-style">
        <el-button type="primary" @click="onCreateSubmit">提交</el-button>
        <el-button type="danger" @click="onCancelSubmit">清空</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="responseDataTable" style="width: 100%;" class="data-table center-style" :preserve-expanded-content="preserveExpanded">
    <el-table-column type="expand">
      <template #default="props">
        <div>
          <el-button 
            size="small" 
            v-for="(item, index) in props.row.operators"
            :key="index"
            type="info"
            :color="item.color" 
            @click="copyToClipboard(item.phone_number)"
          > 
            {{item.name}} 
          </el-button>
        </div>
      </template>
    </el-table-column>
    <el-table-column type="index" :index="1" max-width="30"/>
    <el-table-column prop="details" label="详情" min-width="300" header-align="center">
      <template #default="{row}">
        <span v-html="row.details"></span>
      </template>
    </el-table-column>


  </el-table>
</template>



<style scoped>


.input-textarea :deep(.el-textarea__inner) {
  height: 300px;
  min-height: 300px; /* 防止被压缩 */
}


.center-style :deep(.el-form-item__content) {
  display: flex;
  justify-content: center; /* 水平居中 */
}

.data-table :deep(.el-table .cell)
{
  padding: 0px;
}

:deep(.highlight) {
  background-color: yellow;
  color: black;
  font-weight: bold;
}


</style>
